/**
 *
 */
package com.nd.android.musicboxlibrary.ui.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.utils.StarAppUtils;
import com.nd.android.musicboxlibrary.GlobalSetting;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.IPlayerManager;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.service.player.MusicService;
import com.nd.android.musicboxlibrary.ui.common.ImageLoaderUtil;
import com.nd.android.musicboxlibrary.ui.player.PlayerActivity;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.nd.android.musicboxlibrary.util.NdThread;
import com.nd.android.musicboxlibrary.util.ToastUtil;

/**
 * 音乐盒入口 <br>
 * Created 2014-10-21 下午5:25:25
 *
 * @author zxq
 * @see
 */
public class MusicBoxEnterView extends LinearLayout implements OnClickListener {
    // 音乐广播接收器
    private BroadcastReceiver mReceiver;
    // 当前播放的音乐
    private MusicInfo mCurrentMusic;
    private ImageView ivMusicIcon;
    private ImageView ivPlay;
    private ImageView ivPause;
    private ImageView ivArrow;
    private TextView tvMusicName;

    /**
     * Creates a new instance of MusicBoxEnter. <br>
     * Created 2014-10-21 下午5:25:58
     *
     * @param context
     *            上下文
     */
    public MusicBoxEnterView(Context context) {
        super(context);
        init();
    }

    /**
     * Creates a new instance of MusicBoxEnter. <br>
     * Created 2014-10-21 下午5:26:08
     *
     * @param context
     *            上下文
     * @param attrs
     *            控件参数
     */
    public MusicBoxEnterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    /**
     * Creates a new instance of MusicBoxEnter. <br>
     * Created 2014-10-21 下午5:25:32
     *
     * @param context
     *            上下文
     * @param attrs
     *            控件参数
     * @param defStyle
     *            样式
     */
    @SuppressLint("NewApi")
    public MusicBoxEnterView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        if (View.VISIBLE == visibility) {
            registerReceiver();
            updateMusicInfo();
        } else if (View.GONE == visibility) {
            unregisterReceiver();
        }
    }

    /**
     * 注册广播 <br>
     * Created 2014-11-3 下午10:54:10
     *
     * @author zxq
     */
    private void registerReceiver() {
        unregisterReceiver();
        if (mReceiver == null) {
            mReceiver = new MusicReceiver();
        }
        getContext().getApplicationContext().registerReceiver(mReceiver,
                new IntentFilter(MusicBoxUtils.getMusicServiceAction()));
    }

    /**
     * 注销广播 Created 2014-11-3 下午10:53:14
     *
     * @author zxq
     */
    private void unregisterReceiver() {
        if (mReceiver != null) {
            try {
                getContext().getApplicationContext().unregisterReceiver(mReceiver);
            } catch (IllegalArgumentException e) {
                Log.i(e.getMessage().toString());
            }
            mReceiver = null;
        }
    }

    /**
     * 初始化 <br>
     * Created 2014-10-21 下午5:32:56
     *
     * @author zxq
     */
    private void init() {
        inflate(getContext(), R.layout.mbx_music_box_enter, this);
        ivMusicIcon = (ImageView) findViewById(R.id.iv_enter_music_icon);
        ivPlay = (ImageView) findViewById(R.id.iv_enter_play);
        ivPause = (ImageView) findViewById(R.id.iv_enter_pause);
        ivArrow = (ImageView) findViewById(R.id.iv_enter_arrow);
        tvMusicName = (TextView) findViewById(R.id.tv_enter_msuic_name);

        //字体
        StarAppUtils.setViewTypeFace((TextView)findViewById(R.id.tv_my_music), false);
        StarAppUtils.setViewTypeFace((TextView)findViewById(R.id.tv_jay_music), false);
        StarAppUtils.setViewTypeFace((TextView)findViewById(R.id.tv_play_list), false);
//        StarAppUtils.setViewTypeFace(tvMusicName, false);

        ivPlay.setOnClickListener(this);
        ivPause.setOnClickListener(this);
        findViewById(R.id.ll_main_musicbox).setOnClickListener(this);
        new NdThread() {
            @Override
            protected void doSuccess(Object result) {
                getContext().startService(new Intent(getContext(),MusicService.class));
                if (mCurrentMusic == null) {
                    getMusicInfo();
                }
            }

            @Override
            protected Object doInBackground() throws NdException {
                try {
                    ManagerFactory.getPlaylistInstance(getContext()).getAlbumList();
                } catch (NdException e) {
                    Log.e(e.getSimpleMsg());
                }
                try {
                    return ManagerFactory.getPlaylistInstance(getContext()).getMusicList();
                } catch (NdException e) {
                    Log.e(e.getSimpleMsg());
                    return e;
                }
            }

            @Override
            protected void doFail(NdException e) {
                if (e != null) {
                    ToastUtil.showLong(getContext(), e.getSimpleMsg());
                }
            }
        }.execute();
    }

    /**
     * 更新音乐信息 Created 2014-11-3 下午11:10:29
     *
     * @author zxq
     */
    private void updateMusicInfo() {
        mCurrentMusic = ManagerFactory.getPlayerInstance().getCurrentMusicInfo();
        if (mCurrentMusic != null) {
            showMusicInfo();
            return;
        }
        ivMusicIcon.setImageResource(R.drawable.mbx_main_music_default);
        showPlayerState(false, false);
        getMusicInfo();
    }

    /**
     * 获取音乐信息 Created 2014-11-4 上午12:15:15
     *
     * @author zxq
     */
    private void getMusicInfo() {
        new NdThread() {
            @Override
            protected Object doInBackground() {
                long musicId = ConfigHelper.getInstance(getContext()).loadLongKey(
                        MusicService.MUSIC_ID, -1);
                return ManagerFactory.getPlaylistInstance(getContext()).findMusic(musicId);
            }

            @Override
            protected void doSuccess(Object result) {
                if (result instanceof MusicInfo) {
                    mCurrentMusic = (MusicInfo) result;
                    showMusicInfo();
                } else {
                    showPlayerState(false, false);
                }
            }

            @Override
            protected void doFail(NdException e) {
                showPlayerState(false, false);
            }
        }.execute();
    }

    /**
     * 显示音乐信息 Created 2014-11-3 下午11:49:28
     *
     * @author zxq
     */
    private void showMusicInfo() {
        ImageLoaderUtil.displayPic(mCurrentMusic.getImgUrl(GlobalSetting.MUSIC_ICON_SIZE),
                ivMusicIcon);
        tvMusicName.setText(mCurrentMusic.getMusicName());
        int playerState = ManagerFactory.getPlayerInstance().getPlayerState();
        boolean isPlaying = (playerState == IPlayerManager.PLAYER_STATE_PLAYING
                || playerState == IPlayerManager.PLAYER_STATE_PREPARING);
        showPlayerState(true, isPlaying);
    }

    /**
     * 显示播放状态 Created 2014-11-3 下午11:15:07
     *
     * @param hasMusicInfo boolean
     * @param isPlaying boolean
     * @author zxq
     */
    private void showPlayerState(boolean hasMusicInfo, boolean isPlaying) {
        ivArrow.setVisibility(hasMusicInfo ? View.GONE : View.VISIBLE);
        if (hasMusicInfo) {
            ivPause.setVisibility(isPlaying ? View.VISIBLE : View.GONE);
            ivPlay.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
        } else {
            ivPause.setVisibility(View.GONE);
            ivPlay.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        // 播放
        if (id == R.id.iv_enter_play && mCurrentMusic != null) {
            ManagerFactory.getPlayerInstance().play(getContext());
            showPlayerState(true, true);
            // ivPlay.setVisibility(View.GONE);
            // ivPause.setVisibility(View.VISIBLE);
            // ivArrow.setVisibility(View.GONE);

            // 暂停
        } else if (id == R.id.iv_enter_pause && mCurrentMusic != null) {
            ManagerFactory.getPlayerInstance().pause(getContext());
            showPlayerState(true, false);
            // ivPlay.setVisibility(View.VISIBLE);
            // ivPause.setVisibility(View.GONE);
            // ivArrow.setVisibility(View.GONE);

            // 进入
        } else if (id == R.id.ll_main_musicbox) {
            Intent intent = new Intent(getContext(), PlayerActivity.class);
            if (mCurrentMusic != null) {
                intent.putExtra(MusicService.MUSIC_INFO, mCurrentMusic);
            }
            getContext().startActivity(intent);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        unregisterReceiver();
        super.onDetachedFromWindow();
    }

    /**
     * 音乐广播 Created 2014年9月11日 下午11:53:12
     *
     * @author zxq
     * @version HomeActivity
     * @see
     */
    public class MusicReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 音乐广播
            if (action.equals(MusicBoxUtils.getMusicServiceAction())) {
                // 播放进度改变
                if (intent.hasExtra(MusicService.MUSIC_POSITION)) {
                    showPlayerState(true, true);
                    // ivArrow.setVisibility(View.GONE);
                    // ivPlay.setVisibility(View.GONE);
                    // ivPause.setVisibility(View.VISIBLE);
                }
                // 音乐改变
                if (intent.hasExtra(MusicService.MUSIC_INFO)) {
                    mCurrentMusic = (MusicInfo) intent
                            .getSerializableExtra(MusicService.MUSIC_INFO);
                    ImageLoaderUtil.displayPic(
                            mCurrentMusic.getImgUrl(GlobalSetting.MUSIC_IMAGE_SIZE), ivMusicIcon);
                    tvMusicName.setText(mCurrentMusic.getMusicName());
                }
                // 播放动作
                if (intent.hasExtra(MusicService.PLAYER_ACTION)) {
                    int playAction = intent.getIntExtra(MusicService.PLAYER_ACTION,
                            MusicService.ACTION_PLAY);
                    switch (playAction) {
                        // 停止
                        case MusicService.ACTION_STOP:
                            // 暂停
                        case MusicService.ACTION_PAUSE:
                            ivPlay.setVisibility(View.VISIBLE);
                            ivPause.setVisibility(View.GONE);
                            break;

                        default:
                            ivPlay.setVisibility(View.GONE);
                            ivPause.setVisibility(View.VISIBLE);
                            break;
                    }
                    ivArrow.setVisibility(View.GONE);
                }
            }
        }
    }
}
